package com.lengxf.i18n.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

public class I18nCellWriteHandler implements CellWriteHandler {

    private final MessageSource messageSource = SpringUtil.getBean(MessageSource.class);

    @Override
    public void beforeCellCreate(CellWriteHandlerContext context) {
        if (!context.getHead()) {
            return;
        }
        final List<String> originHeadNames = context.getHeadData().getHeadNameList();
        if (CollectionUtil.isEmpty(originHeadNames)) {
            return;
        }
        List<String> newHeadNames = originHeadNames.stream().
                map(headName -> PlaceholderResolver.getDefaultResolver()
                        .resolveByRule(headName, this::getMessage)).
                collect(Collectors.toList());
        context.getHeadData().setHeadNameList(newHeadNames);
    }

    public String getMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(code, null, locale);
    }

}

